<template>
  <div class="map-container">
    <div id="positionMap" class="map" style="height: 250px" />
  </div>
</template>

<script setup>
import mapObj from '@/utils/mapKey.js'
import {
  shallowRef,
  computed,
  watch,
  ref,
  reactive,
  onMounted,
  onBeforeMount
} from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
  securityJsCode: mapObj.securityJsCode
}
const emit = defineEmits([
  'update:longitude',
  'update:latitude',
  'update:address',
  'cancel',
  'getDistance'
])
const props = defineProps({
  longitude: {
    type: String,
    default: ''
  },
  latitude: {
    type: String,
    default: ''
  },
  address: {
    type: String,
    default: ''
  }
})
const map = shallowRef(null)

const state = reactive({
  autoOptions: {},
  searchText: '',
  map: null,
  marker: null,
  search: null,
  geocoder: null
})

let placeSearch, AMapObj, marker, geocoder

const GetDistance = (lat1, lng1, lat2, lng2) => {
  var radLat1 = (lat1 * Math.PI) / 180.0
  var radLat2 = (lat2 * Math.PI) / 180.0
  var a = radLat1 - radLat2
  var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0
  var s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    )
  s = s * 6378.137 // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000
  return s
}

const initMap = () => {
  AMapLoader.load({
    key: mapObj.key, // 申请好的Web端Key，首次调用 load 时必填
    version: '2.0'
  }).then(AMap => {
    AMapObj = AMap
    map.value = new AMap.Map('positionMap', {
      //设置地图容器id
      viewMode: '3D', //是否为3D地图模式
      zoom: 10, //初始化地图级别
      center: [113.266887, 23.133306] //初始化地图中心点位置
    })

    AMap.plugin(
      [
        // 'AMap.ToolBar',
        // 'AMap.Scale',
        'AMap.Geolocation'
      ],
      () => {
        // 定位
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 10000, //超过10秒后停止定位，默认：5s
          position: 'RT', //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: false //定位成功后是否自动调整地图视野到定位点
          // panToLocation: false,
        })
        map.value.addControl(geolocation)
        geolocation.getCurrentPosition(function (status, result) {
          console.log(result)
          if (status == 'complete') {
            console.log(
              '经度' + result.position.lat + '纬度' + result.position.lng
            )
            let res = GetDistance(
              result.position.lat,
              result.position.lng,
              props.latitude,
              props.longitude
            )
            emit('getDistance', res)
            if (props.latitude) {
              drawMarker(props.longitude, props.latitude)
            }
          } else {
            console.log(result.message)
          }
        })
      }
    )
  })
}

// 绘制地点marker
const drawMarker = (long, lat) => {
  const longitude = long
  const latitude = lat
  if (marker) {
    marker.setMap(null)
  }
  marker = new AMapObj.Marker({
    position: new AMapObj.LngLat(longitude, latitude),
    anchor: 'bottom-center'
  })
  map.value.add(marker)
  map.value.setZoomAndCenter(16, [longitude, latitude])
}

const cancel = () => {
  emit('cancel')
}

onMounted(() => {
  initMap()
})
</script>

<style lang="scss" scoped>
// .map-wrapper {
//   position: relative;
//   width: 100%;
//   height: 400px;
//   #positionMap {
//     width: 100%;
//     height: 100%;
//   }
//   .search-box {
//     position: absolute;
//     left: 30px;
//     top: 80px;
//     z-index: 1;
//     display: flex;
//     align-items: center;
//   }
// }
.map-container {
  width: 100%;
}
.search-input {
  position: absolute;
  left: 30px;
  top: 80px;
  z-index: 1;
  display: flex;
  align-items: center;
}
</style>
